var oddsUpStr = " <span class=\"oddsUp\"></span>";
var oddsDownStr = " <span class=\"oddsDown\"></span>";
//auto refresh all
var autorefreshcounter = 0;

var pushPage;
var engineRef = null;

function onEngineReady(lsEngine) {
    // store the engine reference
    engineRef = lsEngine;

    if (top.matchEmsStatus == 1 && engineRef) {
        engineRef.changeStatus("STREAMING");
    }
}

function onEngineLost() {
    engineRef = null;
}
function executeAutoRefreshByPush() {
    if (typeof (schema) == "undefined")
        return;

    var masterWinRef = top.document.getElementById('push_engine') ? top.document.getElementById('push_engine').contentWindow : null;

    // these two functions are defined in misc.js
    pushPage = initializePushPage("/info/include/js/commons/custom/", oddsPushIconDisplay, onEngineReady, onEngineLost);
    initializeEngine(pushPage, "/info/include/js/commons/lightstreamer/", null, masterWinRef);

    autoRefreshByPush(true, '');
}

var pushJsonSchema = '';
var schemas_array = new Array();
function autoRefreshByPush(isLiveBetting, oddType_Page) {
/*
    var matchStatusList = new Array("MATCH_STATUS");
    var matchStatusSchemaList = new Array("EMS_STATUS");
    var pushstatustable = new NonVisualTable(matchStatusList, matchStatusSchemaList, "MERGE");
    pushstatustable.setDataAdapter("MATCH_STATUS");
    pushstatustable.setSnapshotRequired(true);
    pushstatustable.onItemUpdate = function (itemPos, updateInfo) {
        if (updateInfo.getNewValue("EMS_STATUS") == null
            || updateInfo.getNewValue("EMS_STATUS") == 0) {
            top.matchEmsStatus = 0;
            AMS.disconnect();
        }
    };
    pushPage.addTable(pushstatustable, "status");
*/
    var matches_array = new Array("PAGES");
    schemas_array = new Array();
    if (pageName == "MIXALLUP" || pageName == "MIXALLUPSHORTCUT") {
        var tIds = tMatchID.split(',');
        for (var i = 0; i < tIds.length; i++) {
            schemas_array.push("match_" + tIds[i]);
        }
    }
    else if (pageName == "ALL" || pageName == "INPLAYALL") {
        pushJsonSchema = "match_" + tMatchID;
        schemas_array.push(pushJsonSchema);
    }
    else if (pageName == "TOURN") {
        pushJsonSchema = "tournament_" + pTournID;
        schemas_array.push(pushJsonSchema);
    }
    else {
        pushJsonSchema = schema;
        schemas_array.push(pushJsonSchema);
        if (pageName == "SPC")
            schemas_array.push("odds_tspc_aspx");
    }
    schemas_array.push("CURRENT_MACHINE");
    schemas_array.push("EMS_STATUS");

    var table = new NonVisualTable(matches_array, schemas_array, "MERGE");
    //table.setDataAdapter("ODDSPUSHMATCHES");
    table.setDataAdapter("MATCH_FO");
    table.setSnapshotRequired(true);
    table.onItemUpdate = pushUpdate;
    pushPage.addTable(table, "matches");

    autoSwitchToPoolingMode();
    // JW: ODDS PUSH EOF
}

function pushUpdate(itemPos, updateInfo, itemName) {
    if (updateInfo != null) {
        document.getElementById('machineInfo').title = machineId + ' - ' + updateInfo.getNewValue('CURRENT_MACHINE');

        if (updateInfo.getNewValue('EMS_STATUS') == '0') {
            top.matchEmsStatus = 0;
            AMS.disconnect();
            return;
        }

        for (var i = 0; i < schemas_array.length - 1; i++) {
            if (schemas_array[i] == 'CURRENT_MACHINE' || schemas_array[i] =='EMS_STATUS' )
                continue;

            var pushData = updateInfo.getNewValue(schemas_array[i]);

            try {
                var newData = JSON.parse(pushData);
                if (pageName == "SPC" || pageName == "INPLAYSPC") {
                    // Hybrid
                    if (schemas_array[i] == 'odds_spc_aspx') {
                        dataCache[1].matches = filterSPCData(newData, pageName == "INPLAYSPC");
                        removeReferenceMatch(dataCache);
                    }
                    else if (schemas_array[i] == 'odds_tspc_aspx')
                        dataCache[3] = newData;
                    renderSPCTable(dataCache, false);
                } else if (pageName == "CHP") {
                    dataCache = newData;
                    renderCHPTable(dataCache, false);
                } else if (pageName == "ILC") {
                    dataCache[1].matches = newData;
                    renderILCTable(dataCache, false);
                    if ( newData.length > 0 ) {
                      if ( newData[0].psassys!=null && newData[0].psassys.lastdt!=null && newData[0].psassys.lastdt!='' ) {
                        setLastUpdateTime(newData[0].psassys.lastdt);
                      }
                    }
                   // autoRefreshServerTime();
                } else if (pageName == "MIXALLUP" || pageName == "MIXALLUPSHORTCUT") {
                    setNormalMatchFromPushData(newData);
                    // refresh screen after update last leg = schema_array - CURRENT_MACHINE - EMS_STATUS
                    if (i == schemas_array.length - 3)
                        renderAllMatchAllTable(dataCache, false);
                } else if (pageName != "TOURN") {
                    if (pageName == "ALL") {
                        setNormalMatchFromPushData(newData);
                    }
                    else if (pageName == "INPLAYALL") {
                        setInplayAllOddsMatchFromPushData(newData);
                    }
                    else if (pageName=="INDEX" || pageName=="INPLAYHAD" || pageName=="DHCP" || pageName=="HFMP") {
                        dataCache = newData;
                    }
                    else {
                        dataCache[1].matches = newData;
                        removeReferenceMatch(dataCache);
                    }
                    renderMatchTable(dataCache, false);
                } else {
                    dataCache = newData;
                    renderTournTable(dataCache, false);
                }
            } catch (ex) {
                debugLog("invalid JSON: " + ex);
            }
        }
        displayRemarks();
    }
}

function removeReferenceMatch(data) {
    if (data[2].matches == null)
        return;
    for (var i = data[2].matches.length - 1; i>=0; i--) {
        var mId = data[2].matches[i].matchID;
        if (matchExist(data[1].matches, mId))
            data[2].matches.splice(i,1);
    }
}

function matchExist(matchArray, mId) {
    if (matchArray == null)
        return false;
    for (var i = 0; i < matchArray.length; i++) {
        if (matchArray[i].matchID == mId)
            return true;
    }
    return false;
}

function setAllOddsMatchFromPushData(match, anyOddsExist) {
    dataCache = rawDataForAllOdds;
    for (var i = 0;i<dataCache.length; i++) {
        if (dataCache[i].matchID == match.matchID) {
            if (isValidMatchStatusForNormalMatchList(match.matchStatus) && anyOddsExist)
                dataCache[i] = match;
            else
                dataCache.splice(i, 1);
        }
    }
}

function cloneMatchInfo(match) {
    var cloneMatch = {};
    cloneMatch["matchID"] = match["matchID"];
    cloneMatch["matchIDinofficial"] = match["matchIDinofficial"];
    cloneMatch["matchNum"] = match["matchNum"];
    cloneMatch["matchDate"] = match["matchDate"];
    cloneMatch["matchDay"] = match["matchDay"];
    cloneMatch["homeTeam"] = match["homeTeam"];
    cloneMatch["awayTeam"] = match["awayTeam"];
    cloneMatch["matchStatus"] = match["matchStatus"];
    cloneMatch["matchTime"] = match["matchTime"];
    cloneMatch["league"] = match["league"];
    cloneMatch["coupon"] = match["coupon"];
    cloneMatch["neutralgroundvenue"] = match["neutralgroundvenue"];
    cloneMatch["statuslastupdated"] = match["statuslastupdated"];
    cloneMatch["accumulatedscore"] = match["accumulatedscore"];
    cloneMatch["definedPools"] = match["definedPools"];
    cloneMatch["inplayPools"] = match["inplayPools"];
    cloneMatch["cornerresult"] = match["cornerresult"];
    cloneMatch["results"] = match["results"];
    cloneMatch["inplaydelay"] = match["inplaydelay"];
    cloneMatch["channel"] = match["channel"];
    cloneMatch["liveEvent"] = match["liveEvent"];
    cloneMatch["hasExtraTimePools"] = match["hasExtraTimePools"];
    return cloneMatch;
}

function setNormalMatchFromPushData(match) {
    var cloneMatch = cloneMatchInfo(match);
    cloneMatch["Cur"] = match["Cur"];
    var anyOddsExist = false;
    var hasHADPool = false;

    if (match['inplayPools'].length == 0 && !isValidMatchStatusForNormalMatchListNonInplayPool(match['matchStatus'])) {
        setAllOddsMatchFromPushData(cloneMatch, false);
        return;
    }

    if (isValidPoolStatusForNormalMatchList(match["hadodds"]) && hasValidOdds(match["hadodds"], "HAD")) {
        cloneMatch["hadodds"] = match["hadodds"];
        hasHADPool = true;
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["tqlodds"]) && hasValidOdds(match["tqlodds"], "TQL")) {
        cloneMatch["tqlodds"] = match["tqlodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["hilodds"]) && hasValidOdds(match["hilodds"], "HIL")) {
        cloneMatch["hilodds"] = match["hilodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["chlodds"]) && hasValidOdds(match["chlodds"], "CHL")) {
        cloneMatch["chlodds"] = match["chlodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["crsodds"]) && hasValidOdds(match["crsodds"], "CRS")) {
        cloneMatch["crsodds"] = match["crsodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["hhaodds"]) && hasValidOdds(match["hhaodds"], "HHA")) {
        cloneMatch["hhaodds"] = match["hhaodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["hftodds"]) && hasValidOdds(match["hftodds"], "HFT")) {
        cloneMatch["hftodds"] = match["hftodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["fhaodds"]) && hasValidOdds(match["fhaodds"], "FHA")) {
        cloneMatch["fhaodds"] = match["fhaodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["hdcodds"]) && hasValidOdds(match["hdcodds"], "HDC")) {
        cloneMatch["hdcodds"] = match["hdcodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["fhlodds"]) && hasValidOdds(match["fhlodds"], "FHL")) {
        cloneMatch["fhlodds"] = match["fhlodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["fcsodds"]) && hasValidOdds(match["fcsodds"], "FCS")) {
        cloneMatch["fcsodds"] = match["fcsodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["ftsodds"]) && hasValidOdds(match["ftsodds"], "FTS")) {
        cloneMatch["ftsodds"] = match["ftsodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["fgsodds"]) && hasValidOdds(match["fgsodds"], "FGS")) {
        cloneMatch["fgsodds"] = match["fgsodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["ttgodds"]) && hasValidOdds(match["ttgodds"], "TTG")) {
        cloneMatch["ttgodds"] = match["ttgodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForNormalMatchList(match["ooeodds"]) && hasValidOdds(match["ooeodds"], "OOE")) {
        cloneMatch["ooeodds"] = match["ooeodds"];
        anyOddsExist = true;
    }

    tmpOdds = getValidStatusSPCPoolForNormalMatch(match["spcodds"]);
    if (tmpOdds != null) {
        cloneMatch["spcodds"] = tmpOdds;
        anyOddsExist = true;
    }

    var anySell = anyInplaySelling(match);
    if (!hasHADPool && anyOddsExist && anySell > -1)
        cloneMatch['anyInplaySelling'] = '' + anySell;

    setAllOddsMatchFromPushData(cloneMatch, anyOddsExist);
}

function setInplayAllOddsMatchFromPushData(match) {
    var cloneMatch = cloneMatchInfo(match);
    var anyOddsExist = false;

    if (isValidPoolStatusForInplayMatchList(match["hadodds"], false)) {
        cloneMatch["hadodds"] = match["hadodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForInplayMatchList(match["tqlodds"], false)) {
        cloneMatch["tqlodds"] = match["tqlodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForInplayMatchList(match["hilodds"], false)) {
        cloneMatch["hilodds"] = match["hilodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForInplayMatchList(match["chlodds"], false)) {
        cloneMatch["chlodds"] = match["chlodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForInplayMatchList(match["crsodds"], false)) {
        cloneMatch["crsodds"] = match["crsodds"];
        anyOddsExist = true;
    }
    if (isValidPoolStatusForInplayMatchList(match["hhaodds"], false)) {
        cloneMatch["hhaodds"] = match["hhaodds"];
        anyOddsExist = true;
    }

    if (!is1stHalfResultFinal(cloneMatch) && isValidPoolStatusForInplayMatchList(match["hftodds"], false)) {
        cloneMatch["hftodds"] = match["hftodds"];
        anyOddsExist = true;
    }

    var tmpOdds = getValidStatusPoolListForInplay(match["ntsodds"], "NTS");
    if (tmpOdds != null) {
        cloneMatch["ntsodds"] = tmpOdds;
        anyOddsExist = true;
    }
    tmpOdds = getValidStatusPoolListForInplay(match["etsodds"], "ETS");
    if (tmpOdds != null) {
        cloneMatch["etsodds"] = tmpOdds;
        anyOddsExist = true;
    }
    if (cloneMatch["ntsodds"] == null && cloneMatch["etsodds"] == null) {
        var tmpArr = $.grep(match["definedPools"], function (n, i) { return n == "NTS" || n == "ETS"; });
        if ( tmpArr.length>0 )
            cloneMatch["ntsodds"] = getEmptyNTSList();
    }
    tmpOdds = getValidStatusSPCPoolForInplay(match["spcodds"]);
    if (tmpOdds != null) {
        cloneMatch["spcodds"] = tmpOdds;
        anyOddsExist = true;
    }

    if (isValidPoolStatusForNormalMatchList(match["chpodds"])) {
        cloneMatch["chpodds"] = match["chpodds"];
        anyOddsExist = true;
    }

    setAllOddsMatchFromPushData(cloneMatch, anyOddsExist);
}

function isValidMatchStatusForNormalMatchListNonInplayPool(status) {
    return "Initial" == status
        || "Defined" == status;
}

function isValidMatchStatusForNormalMatchList(status) {
    return "Initial" == status
        || "Defined" == status
        || "Closed" == status
        || "ResultIn" == status
        || "Abandoned" == status;
}

function isValidPoolStatusForInplayMatchList(dict, isETS) {
    return dict != null && (isETS || dict["INPLAY"] == "true") && isValidPoolStatusForNormalMatchList(dict);
}

function isValidPoolStatusForNormalMatchList(dict) {
    if (dict == null || dict["POOLSTATUS"]==null)
        return false;

    var status = dict["POOLSTATUS"];
    return "Initial" == status
        || "Defined" == status
        || "Selling" == status
        || "NotSelling" == status
        || "FinalStopSell" == status
        || "RefundBeforeClosed" == status;
}

function getValidStatusPoolListForInplay(dicts, betType) {
    if (dicts == null)
        return null;

    var newDicts = new Array();
    for(var idx in dicts) {
        if (isValidPoolStatusForInplayMatchList(dicts[idx], "ETS" == betType)
            && hasValidOdds(dicts[idx], betType))
            newDicts.push(dicts[idx]);
    }
    if (newDicts.length > 0)
        return newDicts;
    return null;
}

function getValidStatusSPCPoolForNormalMatch(dicts) {
    if (dicts == null)
        return null;

    var newDicts = new Array();
    for(var idx in dicts) {
        if (isValidPoolStatusForNormalMatchList(dicts[idx]) && hasValidOdds(dicts[idx], "SPC"))
            newDicts.push(dicts[idx]);
    }
    if (newDicts.length > 0)
        return newDicts;
    return null;
}

function getValidStatusSPCPoolForInplay(dicts) {
    if (dicts == null)
        return null;

    var newDicts = new Array();
    for (var idx in dicts) {
        if (isValidPoolStatusForInplayMatchList(dicts[idx], false))
            newDicts.push(dicts[idx]);
    }
    if (newDicts.length > 0)
        return newDicts;
    return null;
}

function is1stHalfResultFinal(match) {
    if (match["accumulatedscore"] != null) {
        for (var idx in match["accumulatedscore"]) {
            if ("FirstHalf" == match["accumulatedscore"][idx].periodvalue
                && "ResultFinal" == match["accumulatedscore"][idx].periodstatus)
                return true;
        }
    }
    return false;
}

function updatePushAllOdds() {
    if (oddsRefreshType != 'push')
        return;

    if (pageName != "ALL" && pageName != "INPLAYALL")
        return;

    if (pushPage.getTable("matches") != null)
        pushPage.removeTable("matches");

    var matches_array = new Array("PAGES");
    schemas_array = new Array();
    pushJsonSchema = "match_" + tMatchID;
    schemas_array.push(pushJsonSchema);
    schemas_array.push("CURRENT_MACHINE");

    var table = new NonVisualTable(matches_array, schemas_array, "MERGE");
    //table.setDataAdapter("ODDSPUSHMATCHES");
    table.setDataAdapter("MATCH_FO");
    table.setSnapshotRequired(true);
    table.onItemUpdate = pushUpdate;
    pushPage.addTable(table, "matches");
}

function hasValidOdds(poolDict, betType) {
    if (poolDict == null)
        return false;

    switch (betType) {
        case "HAD":
        case "FHA":
        case "HHA":
        case "HDC":
        case "FTS":
        case "NTS":
        case "ETS":
        case "TQL":
            return poolDict["H"]!=null;
        case "HIL":
        case "FHL":
        case "CHL":
            return poolDict["LINELIST"] != null && poolDict["LINELIST"].length > 0;
        case "CRS":
        case "FCS":
            return poolDict["S0000"]!=null;
        case "OOE":
            return poolDict["O"]!=null;
        case "TTG":
            return poolDict["P0"]!=null;
        case "HFT":
            return poolDict["HH"]!=null;
        case "FGS":
        case "SPC":
            return poolDict["SELLIST"]!=null && poolDict["SELLIST"].length > 0;
        default:
            break;
    }
    return false;
}

function filterSPCData(data, isIPSPC) {
    if (!isIPSPC)
        return data;

    var nData = [];
    for (var idx = 0; idx < data.length; idx++) {
        var spcData = [];
        for (idy = 0; idy < data[idx].spcodds.length; idy++) {
            if (data[idx].spcodds[idy].INPLAY == "true") {
                spcData.push(data[idx].spcodds[idy]);
            }
        }
        if (spcData.length > 0) {
            data[idx].spcodds = spcData;
            nData.push(data[idx]);
        }
    }
    return nData;
}

function getEmptyNTSList()
{
    var poolList = new Array();
    var poolDict = {};
    poolDict["A"] = "000@0.0";
    poolDict["N"] = "000@0.0";
    poolDict["H"] = "000@0.0";
    poolDict["POOLSTATUS"] = "Initial";
    poolDict["INPLAY"] = "true";
    poolDict["ALLUP"] = "true";
    poolDict["ITEM"] = "1";
    poolDict["Cur"] = "0";
    poolList.push(poolDict);
    return poolList;
}

function isAnyOddsExist(match) {
    var anyOddsExist = match.hadodds != null
        || match.fhaodds != null
        || match.crsodds != null
        || match.fcsodds != null
        || match.ftsodds != null
        || match.tqlodds != null
        || match.ooeodds != null
        || match.ttgodds != null
        || match.hftodds != null
        || match.hhaodds != null
        || match.hdcodds != null
        || match.hilodds != null
        || match.fhlodds != null
        || match.chlodds != null
        || match.fgsodds != null
        || match.spcodds != null
        || match.ntsodds != null
        || match.etsodds != null
        || match.chpodds != null;
    return anyOddsExist;
}

// 1 = selling, 0 = not selling, -1 = other status
function getSellValue(dict) {
    if (dict == null)
        return -1;
    if ("0"==dict["Cur"])
        return -1;

    var status = dict["POOLSTATUS"];
    switch (status) {
        case "Selling":
            return 1;
        case "NotSelling":
        case "FinalStopSell":
        case "Defined":
        case "RefundBeforeClosed":
            return 0;
        default:
            break;
    }
    return -1;
}

// for NTS, ETS and SPC
function getSellValueFromList(dicts) {
    if (dicts == null)
        return -1;

    for(var idx in dicts) {
        var sVal = getSellValue(dicts[idx]);
        if (sVal > -1)
            return sVal;
    }
    return -1;
}

function anyInplaySelling(m) {
    var sellVal = -1;
    sellVal = Math.max(sellVal, getSellValue(m.hadodds));
    sellVal = Math.max(sellVal, getSellValue(m.tqlodds));
    sellVal = Math.max(sellVal, getSellValueFromList(m.etsodds));
    sellVal = Math.max(sellVal, getSellValueFromList(m.ntsodds));
    sellVal = Math.max(sellVal, getSellValue(m.crsodds));
    sellVal = Math.max(sellVal, getSellValue(m.hilodds));
    sellVal = Math.max(sellVal, getSellValue(m.chlodds));
    sellVal = Math.max(sellVal, getSellValue(m.hhaodds));
    sellVal = Math.max(sellVal, getSellValue(m.hftodds));
    sellVal = Math.max(sellVal, getSellValueFromList(m.spcodds));

    if ( sellVal > -1 )
        sellVal = Math.max(sellVal, getSellValue(m.chpodds));
    return sellVal;
}